package com.aquarium.ui;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;

import javax.mail.internet.NewsAddress;

import com.aquarium.alarm.AlarmManager;
import com.aquarium.bt.BTManager;
import com.aquarium.data.HistoryDataBase;
import com.aquarium.mail.MailInfo;
import com.aquarium.mail.MailSender;
import com.aquarium.sensor.SensorManager;
import com.aquarium.util.DialogUtils;
import com.aquarium.util.NotificationUtils;
import com.aquarium.util.SPUtils;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class AlarmService extends Service implements Observer {
	private String TAG = "AlarmService";

	private SensorManager mSensorManager;
	private AlarmManager mAlarmManager;
	private MailInfo mailInfo;
	private MailSender mailSender;
	private BTManager mBTManager;
	private float mCurrentPhValue;
	private float mCurrentTemperatureValue;
	private float mCurrentOxygenValue;
	private float mCurrentConductivityValue;
	private float mCurrentWaterLevelValue;

	private HashMap<String, String> mSensorValueMap;
	HistoryDataBase historyDataBase;
	private long STORE_STAMP = 1 * 60 * 60 * 1000;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.d(TAG, "onCreate");
		mSensorManager = SensorManager.getInstance();
		mSensorManager.addObserver(this);
		mAlarmManager = AlarmManager.getInstance(this);
		// updateAlarmValue();
		// mSensorManager.notifySensorValueTest();
		mailInfo = MailInfo.getInstance(this);
		mailSender = new MailSender(this);
		mBTManager = BTManager.getInstance();
		// mBTManager.sendSensorValueTest();
		historyDataBase = HistoryDataBase.getInstance(this);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// mSensorManager.stopNotifySensorValueTest();
		// mBTManager.stopSendSensorValueTest();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void update(Observable observable, Object data) {
		if (observable instanceof SensorManager) {
			mSensorValueMap = (HashMap<String, String>) data;
			mCurrentPhValue = Float.parseFloat(mSensorValueMap
					.get(SensorManager.PH_VALUE_KEY));
			mCurrentTemperatureValue = Float.parseFloat(mSensorValueMap
					.get(SensorManager.TEMPERATURE_VALUE_KEY));
			mCurrentOxygenValue = Float.parseFloat(mSensorValueMap
					.get(SensorManager.OXYGEN_VALUE_KEY));
			mCurrentConductivityValue = Float.parseFloat(mSensorValueMap
					.get(SensorManager.CONDUCTIVITY_VALUE_KEY));
			mCurrentWaterLevelValue = Float.valueOf(mSensorValueMap
					.get(SensorManager.WATER_LEVEL_VALUE_KEY));
			// if (mCurrentConductivityValue == 0 || mCurrentOxygenValue == 0
			// || mCurrentPhValue == 0 || mCurrentTemperatureValue == 0
			// || mCurrentWaterLevelValue == 0) {
			// return;
			// }
			if (historyDataBase == null) {
				historyDataBase = historyDataBase.getInstance(this);
			}
			String str = historyDataBase
					.queryKeyValue(HistoryDataBase.STORE_SENSOR_VALUE_TIME);
			if (str == null) {
				Log.d(TAG, " str is null");
				synchronized (this) {
					long timeStamp = System.currentTimeMillis();
					SimpleDateFormat dateformat1 = new SimpleDateFormat(
							"yyyy/MM/dd HH:mm");
					String date = dateformat1.format(new Date());
					historyDataBase.insertHistoryItem(date, mSensorValueMap);
					historyDataBase.updateKeyValue(
							HistoryDataBase.STORE_SENSOR_VALUE_TIME,
							String.valueOf(timeStamp));
				}

				Log.d(TAG, " str is null over");
			} else {

				long timeStamp = Long.valueOf(str);
				long Interval = Math
						.abs(timeStamp - System.currentTimeMillis());
				if (Interval > STORE_STAMP) {
					Log.d(TAG, "Interval > STORE_STAMP");
					String time = String.valueOf(System.currentTimeMillis());
					SimpleDateFormat dateformat1 = new SimpleDateFormat(
							"yyyy/MM/dd HH:mm");
					String date = dateformat1.format(new Date());
					historyDataBase.insertHistoryItem(date, mSensorValueMap);
					historyDataBase.updateKeyValue(
							HistoryDataBase.STORE_SENSOR_VALUE_TIME, time);
				}
			}

		}

		else {
			Log.e(TAG, "update,error data ");
		}

		if (alarmInfo() != null
				&& mAlarmManager.isNeedAlarm()
				&& (mAlarmManager.isPhoneEnable()
						|| mAlarmManager.isRangEnable() || mailInfo
							.isEmailEnable())) {
			Log.d(TAG, "start alarm ");
			NotificationUtils.show(this, alarmInfo().split(";"));
			if (mAlarmManager.isPhoneEnable()) {
				Log.d(TAG, "start sms true");
				mAlarmManager.sendSms(alarmInfo());
			} else {
				Log.d(TAG, "mAlarmManager.isPhoneEnable() false");
			}
			if (mAlarmManager.isRangEnable()) {
				Log.d(TAG, "start rang true");
				mAlarmManager.rang();
			} else {
				Log.d(TAG, "mAlarmManager.isRangEnable() false");
			}
			if (mailInfo.isEmailEnable()) {
				Log.d(TAG, "start mail true");

				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						mailSender.sendTextMail(alarmInfo());
					}
				}).start();

				// mailSender.sendTextMail(alarmInfo());

			} else {
				Log.d(TAG, "mailSenderInfo.isEmailEnable() false");
			}
			mAlarmManager.setAlarmTime();

		}
	}

	private String alarmInfo() {
		return (mAlarmManager.alarmPhInfo(mCurrentPhValue)
				+ mAlarmManager
						.alarmConductivityInfo(mCurrentConductivityValue)
				+ mAlarmManager.alarmOxygenInfo(mCurrentOxygenValue)
				+ mAlarmManager.alarmTemperatureInfo(mCurrentTemperatureValue) + mAlarmManager
					.alarmWaterLevelInfo(mCurrentWaterLevelValue)).replaceAll(
				"null", "");
	}

}
